package com.lhb.aicodemother.controller;

import com.lhb.aicodemother.constant.AppConstant;
import com.lhb.aicodemother.model.entity.App;
import com.lhb.aicodemother.service.AppService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import java.io.File;

/*
* 用于预览AI生成的网站
* */
@RestController
@RequestMapping("/static")
public class StaticResourceController {

    @Resource
    AppService appService;

    // 应用生成根目录
    private static final String PREVIEW_ROOT_DIR = AppConstant.CODE_OUTPUT_ROOT_DIR;

    /*
    * 提供静态资源访问，支持目录重定向
    * 访问格式：http://localhost:8123/api/static/{appId}[/{fileName}]
    * */
    @GetMapping("/{appId}/**")
    public ResponseEntity<FileSystemResource> serveStaticResource(@PathVariable String appId, HttpServletRequest request) {
        try{
            // 获取资源路径
            String resourcePath = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            resourcePath = resourcePath.substring(("/static/" + appId).length());
            // 如果是目录访问，重定向到带斜杆的URL
            if(resourcePath.isEmpty()){
                HttpHeaders headers = new HttpHeaders();
                headers.add("Location",request.getRequestURI() + "/");
                return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
            }
            // 默认返回index.html
            if(resourcePath.equals("/")){
                resourcePath = "index.html";
            }
            App app = appService.getById(appId);
            if(app == null){
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            // 构建文件路径
            String filePath = PREVIEW_ROOT_DIR + "/" + app.getCodeGenType() + "_" + appId + "/" + resourcePath;
            File file = new File(filePath);
            // 检查文件是否存在
            if(!file.exists()){
                return ResponseEntity.notFound().build();
            }
            // 返回文件资源
            FileSystemResource resource = new FileSystemResource(file);
            return ResponseEntity.ok()
                    .header("Content-Type",getContentTypeWithCharset(filePath))
                    .body(resource);
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /*
    * 根据文件扩展名返回带字符编码的Content-Type
    * */
    private String getContentTypeWithCharset(String filePath){
        if(filePath.endsWith(".html")) return "text/html;charset=utf-8";
        if(filePath.endsWith(".css")) return "text/css;charset=utf-8";
        if(filePath.endsWith(".js")) return "application/javascript;charset=utf-8";
        if(filePath.endsWith(".png")) return "image/png";
        if(filePath.endsWith(".jpg")) return "image/jpeg";
        return "application/octet-stream";
    }
}
